package {
	import as3isolib.display.IsoGroup;
	import as3isolib.display.primitive.IsoBox;
	import as3isolib.display.renderers.DefaultSceneLayoutRenderer;
	import as3isolib.display.scene.IsoGrid;
	import as3isolib.graphics.SolidColorFill;
	import de.polygonal.ds.Array2;

	/**
	 */
	public class Group extends IsoGroup {
		protected var _layout:Array2;
		protected var _grid:IsoGrid;

		public function Group(grid:IsoGrid, descriptor:Object = null) {
			super(descriptor);

			_grid = grid;
			renderer = new DefaultSceneLayoutRenderer();
		}

		public function setMap(map:Array):void {

			if (children.length > 0) {
				removeAllChildren();
			}

			//make NxN array that represents the group's layout 
			//this is the array we'll rotate
			var w:Number = Math.max(map[0].length, map.length);
			_layout = new Array2(w, w);
			_layout.fill(0);

			for (var row:int = 0; row < map.length; row++) {
				var r:Array = map[row];

				for (var col:int = 0; col < r.length; col++) {
					if (map[row][col] != 0) {
						var box:IsoBox = new IsoBox();
						box.fills = [new SolidColorFill(0x00FFFF, 1), new SolidColorFill(0x8080C0, 1), new SolidColorFill(0xFF8040, 1)];
						box.setSize(_grid.cellSize, _grid.cellSize, 40);
						box.moveTo(_grid.cellSize * col, _grid.cellSize * row, 0);
						box.name = map[row][col];
						addChild(box);

						_layout.set(col, row, box);
					}
				}
			}

		}

		public function rotate(clockWise:Boolean = true):void {

			//make a new NxN array for the new layout ( after rotation )
			var w:Number = _layout.width;
			var newLayout:Array2 = new Array2(w, w);
			newLayout.fill(0);

			for (var r:int = 0; r < w; r++) {
				for (var c:int = 0; c < w; c++) {
					//found this array-rotation algo somewhere on the web
					var c0:int = (clockWise == true) ? w - 1 - r : r;
					var r0:int = (clockWise == true) ? c : w - 1 - c;

					newLayout.set(c0, r0, _layout.get(c, r));
				}
			}

			_layout = newLayout;
			updateChildren();

		}

		protected function updateChildren():void {

			for (var r:int = 0; r < _layout.height; r++) {
				for (var c:int = 0; c < _layout.width; c++) {
					if (_layout.get(c, r) is IsoBox) {
						_layout.get(c, r).moveTo(c * _grid.cellSize, r * _grid.cellSize, 0);
					}
				}

			}
		}

		override protected function renderLogic(recursive:Boolean = true):void {

			for each (var child:IsoBox in children) {
				if (child.isInvalidated) {
					renderer.renderScene(this);
					break;
				}
			}
			super.renderLogic(recursive);
		}
	}

}
